package net.sf.rose.business.action.define;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.rose.business.action.Download;
import net.sf.rose.business.bean.action.Action;
import net.sf.rose.business.bean.action.ActionSet;
import net.sf.rose.business.bean.action.FieldBean;
import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.business.service.ActionService;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.web.OnlineUserListener;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能：
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/action")
public class ActionController {

	private static String LIST_PAGE = "define/action/list";
	private static String VIEW_PAGE = "define/action/edit";
	private static String CONSULT_PAGE = "define/action/consult";
	private static String ACTION_SET_TEMP = "BASE_DEFINE_ACTION_SET_TEMP";

	/**
	 * 普通查询
	 */
	@RequestMapping("/list.html")
	public ModelAndView list(HttpServletRequest request, Service service) {
		Map<String, ActionSet> bean = ActionService.getAllActionSet();
		String[] sorts = getActionSorts(request);
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("list", bean);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", "all");
		return mav;
	}

	private String[] getActionSorts(HttpServletRequest request){
		String[] array = null;
		Object obj = request.getSession().getAttribute("action_sorts");
		if (obj == null) {
			Map<String, ActionSet> bean = ActionService.getAllActionSet();
			Set<String> sorts = new HashSet<String>();
			for (Action a : bean.values()) {
				sorts.add(a.getSort());
			}
			array = new String[sorts.size()];
			Object[] objs = sorts.toArray();
			for (int i = 0; i < sorts.size(); i++) {
				array[i] = objs[i].toString();
			}
			request.getSession().setAttribute("action_sorts", array);
		} else {
			array = (String[]) obj;
		}
		return array;
	}

	/**
	 * 普通查询
	 */
	@RequestMapping("/search.html")
	public ModelAndView search(HttpServletRequest request,String sort,String actionName) {
		Map<String, ActionSet> map = null;
		Map<String, ActionSet> bean = ActionService.getAllActionSet();
		if (sort.equals("all")) {
			map = bean;
		} else {
			map = new HashMap<String, ActionSet>();
			for (String key : bean.keySet()) {
				ActionSet a = bean.get(key);
				if (a.getSort().equals(sort)) {
					map.put(key, a);
				}
			}
		}
		if (actionName != null && !actionName.trim().equals("")) {
			String name = actionName.trim();
			Map<String, ActionSet> m = new HashMap<String, ActionSet>();
			for (String key : map.keySet()) {
				ActionSet a = map.get(key);
				if (a.getName().indexOf(name) != -1) {
					m.put(key, a);
				}
			}
			map = m;
		}
		String[] sorts = getActionSorts(request);
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("list", map);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", sort);
		mav.addObject("actionName", actionName);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/add.html")
	public ModelAndView add(HttpServletRequest request) {
		ActionSet bean = new ActionSet();
		// bean.getActionUnits().add("1");
		request.getSession().setAttribute(ACTION_SET_TEMP, bean);
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, String name) {
		Action bean = ActionService.getAction(name);
		request.getSession().setAttribute(ACTION_SET_TEMP, bean);
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/delete.html")
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response, 
			String type, String id) throws Exception {
		ActionService.removeAction(id);
		response.reset();
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		pw.write("{\"msg\":\"删除成功！\"}");
		pw.flush();
		pw.close();
		return null;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/save.html")
	public ModelAndView save(HttpServletRequest request, ActionSet bean) {
		Object temp = request.getSession().getAttribute(ACTION_SET_TEMP);
		if(temp != null){
			ActionSet set = (ActionSet) temp;
			set.setName(bean.getName());
			set.setSort(bean.getSort());
			set.setDescription(bean.getDescription());
			set.setFields(this.getFieldBeanList(request));
			set.setActionType("set");
			ActionService.addAction(set);
		}
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/saveAll.html")
	public ModelAndView saveAll(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		ActionService.save(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/consult.html")
	public ModelAndView consult(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView(CONSULT_PAGE);
		Enumeration<?> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String key = en.nextElement().toString();
			mav.addObject(key,request.getParameter(key));
		}
		String[] sorts = getAllActionSorts(request);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", "all");
		return mav;
	}

	private String[] getAllActionSorts(HttpServletRequest request){
		String[] array = null;
		Object obj = request.getSession().getAttribute("all_action_sorts");
		if (obj == null) {
			Map<String, Action> bean = ActionService.getAll();
			Set<String> sorts = new HashSet<String>();
			for (Action a : bean.values()) {
				sorts.add(a.getSort());
			}
			array = new String[sorts.size()];
			Object[] objs = sorts.toArray();
			for (int i = 0; i < sorts.size(); i++) {
				array[i] = objs[i].toString();
			}
			request.getSession().setAttribute("all_action_sorts", array);
		} else {
			array = (String[]) obj;
		}
		return array;
	}
	
	/**
	 * 参照查询操作，包括操作集和操作
	 */
	@RequestMapping("/consultSearch.html")
	public ModelAndView consultSearch(HttpServletRequest request,String sort,String actionName) {
		Map<String, Action> map = null;
		Map<String, Action> bean = ActionService.getAll();
		if (sort.equals("all")) {
			map = bean;
		} else {
			map = new HashMap<String, Action>();
			for (String key : bean.keySet()) {
				Action a = bean.get(key);
				if (a.getSort().equals(sort)) {
					map.put(key, a);
				}
			}
		}
		if (actionName != null && !actionName.trim().equals("")) {
			String name = actionName.trim();
			Map<String, Action> m = new HashMap<String, Action>();
			for (String key : map.keySet()) {
				Action a = map.get(key);
				if (a.getName().indexOf(name) != -1) {
					m.put(key, a);
				}
			}
			map = m;
		}
		String[] sorts = getAllActionSorts(request);
		ModelAndView mav = new ModelAndView(CONSULT_PAGE);
		Enumeration<?> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String key = en.nextElement().toString();
			mav.addObject(key,request.getParameter(key));
		}
		mav.addObject("list", map);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", sort);
		mav.addObject("actionName", actionName);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/saveTemp.html")
	public ModelAndView saveTemp(HttpServletRequest request) {
		ActionSet set = null;
		Map<String, Object> map = getDecodePostBean(request);
		Object temp = request.getSession().getAttribute(ACTION_SET_TEMP);
		if (temp != null) {
			set = (ActionSet) temp;
			Object obj = map.get("name");
			if (obj != null) {
				set.setName(obj.toString());
			}
			obj = map.get("sort");
			if (obj != null) {
				set.setSort(obj.toString());
			}
			obj = map.get("description");
			if (obj != null) {
				set.setDescription(obj.toString());
			}
			set.setFields(this.getFieldBeanList(map));
			obj = map.get("actionUnits");
			if (obj != null) {
				String[] arr = obj.toString().split(",");
				for (String s : arr) {
					set.getActionUnits().add(s);
				}
			}
		}
		request.getSession().setAttribute(ACTION_SET_TEMP, set);
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", set);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/removeActionUnit.html")
	public ModelAndView removeActionUnit(HttpServletRequest request, String actionUnitName) {
		ActionSet set = null;
		Object temp = request.getSession().getAttribute(ACTION_SET_TEMP);
		if(temp != null){
			set = (ActionSet) temp;
			set.getActionUnits().remove(actionUnitName);
		}
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", set);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/moveActionUnit.html")
	public ModelAndView moveActionUnit(HttpServletRequest request, String actionUnitName,String type) {
		ActionSet set = null;
		Object temp = request.getSession().getAttribute(ACTION_SET_TEMP);
		if(temp != null){
			set = (ActionSet) temp;
			List<String> list = set.getActionUnits();
			int i = list.indexOf(actionUnitName);
			if (i != -1) {
				// 上移
				if (type.equals("up")) {
					if (i > 0) {
						list.remove(i);
						list.add(i - 1, actionUnitName);
					}
				}
				// 下移
				else if (type.equals("down")) {
					if (i < list.size() - 1) {
						list.remove(i);
						list.add(i + 1, actionUnitName);
					}
				}
			}
		}
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", set);
		return mav;
	}

	private List<FieldBean> getFieldBeanList(HttpServletRequest request) {
		List<FieldBean> list = new ArrayList<FieldBean>();
		int i = 0;
		do {
			// 参数的键值
			String key = request.getParameter("items.key[" + i + "]");
			if (key == null || key.equals("")) {
				break;
			}
			FieldBean param = new FieldBean();
			param.setKey(key);
			// 参数的数据类型
			String type = request.getParameter("items.type[" + i + "]");
			if (type != null && !type.equals("")) {
				param.setType(type);
			}
			// 参数的数据格式
			String format = request.getParameter("items.format[" + i + "]");
			if (format != null && !format.equals("")) {
				param.setFormat(format);
			}
			// 如果值为空时使用默认值
			String value = request.getParameter("items.value[" + i + "]");
			if (value != null && !value.equals("")) {
				param.setValue(value);
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}

	private List<FieldBean> getFieldBeanList(Map<String, Object> map) {
		List<FieldBean> list = new ArrayList<FieldBean>();
		int i = 0;
		do {
			// 参数的键值
			Object key = map.get("items.key[" + i + "]");
			if (key == null || key.equals("")) {
				break;
			}
			FieldBean param = new FieldBean();
			param.setKey(key.toString());
			// 参数的数据类型
			Object type = map.get("items.type[" + i + "]");
			if (type != null && !type.equals("")) {
				param.setType(type.toString());
			}
			// 参数的数据格式
			Object format = map.get("items.format[" + i + "]");
			if (format != null && !format.equals("")) {
				param.setFormat(format.toString());
			}
			// 如果值为空时使用默认值
			Object value = map.get("items.value[" + i + "]");
			if (value != null && !value.equals("")) {
				param.setValue(value.toString());
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}
	
	/**
	 * 
	 */
	private Map<String, Object> getDecodePostBean(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String key = null;
			Object val = null;
			Enumeration<?> en = request.getParameterNames();
			while (en.hasMoreElements()) {
				key = en.nextElement().toString();
				val = request.getParameter(key);
				val = java.net.URLDecoder.decode(val.toString(), "UTF-8");
				if (!val.toString().trim().equals("")) {
					map.put(key, val);
				} else {
					map.put(key, null);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return map;
	}
	
	/**
	 * 提交操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/input.html")
	public ModelAndView input(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Download.TEMP_FILES);
		if (obj == null) {
			throw new SystemException("Session中找不到上传的文件。", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		Map<String, DownloadFileBean> map = (Map<String, DownloadFileBean>) obj;
		InputStream in = null;
		try {
			for (DownloadFileBean bean : map.values()) {
				if (bean.getData() != null) {
					in = bean.getData().getInputStream();
				}
			}
		} catch (IOException e) {
			throw new SystemException("上传的文件读取错误 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		if (in == null) {
			throw new SystemException("没有找到上传的文件 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		ActionService.input(in);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "导入成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/output.html")
	public String output(HttpServletRequest request) {
		File file = ActionService.output();
		request.setAttribute(Download.DOWNLOAD_FILE, file);
		request.setAttribute(Download.DOWNLOAD_FILE_NAME, "操作集配置.xml");
		return "forward:/download.html";
	}
}
